#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <errno.h>

const static int MAX_EVENTS = 100;

int set_nonblocking(int fd) 
{
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1) {
        flags = 0;
    }
    return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

int main()
{
    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd < 0) {
        perror("socket failed");
        return -1;
    }

    int opt = 1;
    int n = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    if (n < 0) {
        perror("setsockopt failed");
        close(listenfd);
        return -2;
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(8080);

    n = bind(listenfd, (struct sockaddr*)&addr, sizeof(addr));
    if (n < 0) {
        perror("bind failed");
        close(listenfd);
        return -3;
    }

    n = listen(listenfd, 8);
    if (n < 0) {
        perror("listen failed");
        close(listenfd);
        return -4;
    }

    // 0. 设置 listenfd 非阻塞
    set_nonblocking(listenfd);

    // 1. 创建 epoll 实例
    int epollfd = epoll_create1(EPOLL_CLOEXEC);
    if (epollfd < 0) {
        perror("epoll_create1 failed");
        close(listenfd);
        return -5;
    }

    // 2. 将监听套接字加入 epoll
    struct epoll_event ev;
    ev.data.fd = listenfd;
    ev.events = EPOLLIN | EPOLLET; // ET 模式

    n = epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &ev);


    struct epoll_event events[MAX_EVENTS];
    while (1) {
        // 3. 等待就绪事件
        int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
        if (nfds < 0) {
            perror("epoll_wait failed");
            break;
        }

        for (int i = 0; i < nfds; i++) {
            // 4. 接收新连接
            if (events[i].data.fd == listenfd && (events[i].events & EPOLLIN)) {
                // 循环处理
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);

                while (1) {
                    memset(&peer, 0, sizeof(peer));
                    int clientfd = accept(listenfd, (struct sockaddr*)&peer, &len);
                    if (clientfd < 0) {
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
                            // 连接 accept 完毕
                            break;
                        }
                        else {
                            perror("accept failed");
                            break;
                        }
                    }

                    set_nonblocking(clientfd); // 设置非阻塞

                    struct epoll_event ev;
                    ev.data.fd = clientfd;
                    ev.events = EPOLLIN | EPOLLET;

                    int n = epoll_ctl(epollfd, EPOLL_CTL_ADD, clientfd, &ev);
                    if (n < 0) {
                        perror("epoll_ctl failed");
                        close(clientfd);
                    }
                }
            }
            // 5. 处理客户端数据
            else if (events[i].events & EPOLLIN) {
                int clientfd = events[i].data.fd;
                char buffer[128] = {0};
                // 循环读取
                while (1) {
                    int cnt = recv(clientfd, buffer, 128, 0);
                    if (cnt < 0) {
                        // 读完
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
                            break;
                        }
                        // 异常情况
                        else {
                            perror("recv failed");
                            epoll_ctl(epollfd, EPOLL_CTL_DEL, clientfd, NULL);
                            close(clientfd);
                            break;
                        }
                    }
                    else if (cnt == 0) {
                        epoll_ctl(epollfd, EPOLL_CTL_DEL, clientfd, NULL);
                        close(clientfd);
                        break;
                    }
                    else {
                        buffer[cnt] = 0;
                        printf("clientfd: %d, count: %d, buffer: %s\n", clientfd, cnt, buffer);
                        send(clientfd, buffer, cnt, 0);
                    }
                }
            }
        }
    }

    close(epollfd);
    close(listenfd);

    return 0;
}